<template>
  <div id="myGroup" :style="{ width: group ? '286px' : '100%' }">
    <h1 v-if="group">组织架构</h1>
    <div class="search" v-if="group">
      <el-input
        v-model="searchKeys"
        placeholder="搜索分组或设备..."
        class="input-with-select"
      >
        <template #append>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    <el-tree
      ref="tree"
      :data="treeData"
      :props="{ ...propsData, class: customClassName }"
      node-key="id"
      :expand-on-click-node="true"
      accordion
      :default-expanded-keys="defaultExpandNodes"
      :current-node-key="currentNode"
      highlight-current
      :show-checkbox="!group"
      :filter-node-method="filterNode"
      @node-click="handleCehecClick"
      @check="handleCheck"
      @current-change="handleCurrentChange"
    >
      <template #default="{ node }">
        <span class="custom-tree-node">
          <span class="node-lable">
            <i
              v-if="node.data.type === 'device'"
              :class="node.data.online ? 'is-online' : ''"
            ></i>
            <p
              :title="
                node.data.type === 'device'
                  ? node.label + (node.data.online ? ' 在线' : ' 离线')
                  : node.label
              "
            >
              {{ node.label }}
            </p>
            <span v-if="node.data.type === 'category' && group">{{
              getOnlineNum(node)
            }}</span>
          </span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from "vue";
import { Search, Refresh, Delete, Plus } from "@element-plus/icons-vue";
import { req_loadGroupTree } from "~/utils/axios/common.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTreeStore } from "~/utils/pinia/tree.js";
import { useRouter } from "vue-router";
const tree = ref();
let $router = useRouter();
const treeStore = useTreeStore();
let searchKeys = ref("");
let searchNode = ref(null);
const treeNodes = ref([]);
const currentNode = ref(null);
const defaultExpandNodes = ref([1]);

const filterNode = (value, data) => {
  if (!value || value == "全部分组") return true;
  if (pidlist.value.indexOf(data.pid) != -1 && data.type == "device") {
    return true;
  }
  return data.name.includes(value);
};
const props = defineProps({
  getDeviceId: {
    type: Function,
    default: () => [],
  },
  group: {
    type: Boolean,
    default: true,
  },
});
const propsData = ref({
  label: "name",
  children: "child",
  isLeaf: "leaf",
});
const customClassName = (node) => {
  let className = "";
  if (node.type === "device") {
    className += "node-level3 ";
  }
  if (node.type === "device" && !node.online) {
    className += "node-disabled";
  }
  return className;
};
const getOnlineNum = computed(() => (node) => {
  if (node.data.child)
    return (
      node.data.child.filter((item) => item.online).length + "/" + node.data.child.length
    );
  else return 0 + "/" + 0;
});
const treeData = ref([
  {
    id: 1,
    pid: 0,
    name: "全部分组",
    type: "all",
    child: [],
  },
]);
const noDataFlagWhite = [
  "/serverstrategy",
  "/auditlog",
  "/authunload",
  "/terminalupdate",
  "/categorystrategy",
];
const getTreeData = async () => {
  if (!noDataFlagWhite.includes($router.currentRoute.value.path)) {
    treeStore.showGroupFlag = true;
  }
  let params = {};
  if (treeStore.osType) {
    params.fromOs = treeStore.osVersion || "";
    params.os = treeStore.osType
  }
  const { data: res } = await req_loadGroupTree(params);
  treeData.value[0].child = res;
};
getTreeData();
const loadNode = async (node, resolve) => {
  const noDataFlagWhite = [
    "/serverstrategy",
    "/auditlog",
    "/authunload",
    "/terminalupdate",
  ];
  if (!noDataFlagWhite.includes($router.currentRoute.value.path)) {
    treeStore.showGroupFlag = true;
  }
  if (node.level === 0) {
    data.node = node;
    data.resolveFunc = resolve;
    return resolve([
      {
        id: 1,
        pid: 0,
        name: "全部分组",
        type: "all",
      },
    ]);
  }
  if (node.level === 1) {
    let groupRes = await req_loadGroupTree();
    if (groupRes.status === 200) {
      // let groupData = [];
      // if (!props.group) {
      //   groupRes.data.map((item) => {
      //     item.leaf = true;
      //     if (item.id != 0) {
      //       groupData.push(item);
      //     }
      //   });
      //   return resolve(groupData);
      // } else {
      //   treeNodes.value = groupRes.data;
      //   return resolve(groupRes.data);
      // }
      treeNodes.value = groupRes.data;
      return resolve(groupRes.data);
    }
  }
  if (node.level === 2) {
    setTimeout(() => {
      if (node.data.child) {
        node.data.child.map((item) => {
          item.leaf = true;
          if (item.type === "device" && !item.online) {
            item.customClassName = "node-disabled";
          }
          return item;
        });
        return resolve(node.data.child);
      } else {
        return resolve([]);
      }
    }, 150);
  }
};
const noDataFlagWhite1 = ["/auditlog", "/categorystrategy"];
const handleCurrentChange = (data) => {
  treeStore.treeDeviceId = data.deviceId;
  if (noDataFlagWhite1.includes($router.currentRoute.value.path)) {
    treeStore.showGroupFlag = false;
    treeStore.treeLinkedTableCategoryId = data.id;
  }
  // if ($router.currentRoute.value.path == "/auditlog") {
  //   treeStore.showGroupFlag = false;
  //   treeStore.treeLinkedTableCategoryId = data.id;
  // }
  if (data.child && treeStore.treeLinkedTableRef) {
    treeStore.treeLinkedTableRef.getTableData();
  }
};
// 部门树形组件点击后刷新表格
const handleCehecClick = (data) => {
  // treeStore.treeLinkedTableCategoryId = data.id
  // 这里是针对审计日志，用户需求：在审计日志功能时，点击节点即可查看当前节点下所有设备的数据汇总；
  if (!data.child && noDataFlagWhite1.includes($router.currentRoute.value.path)) {
    treeStore.showGroupFlag = true;
    treeStore.treeLinkedTableCategoryId = null;
  }
  if (data.deviceId) {
    treeStore.treeDeviceId = data.deviceId;
    treeStore.osType = data.osType;
    treeStore.osVersion = data.osVersion
  } else {
    return;
  }
  if (treeStore.treeLinkedTableRef) {
    treeStore.treeLinkedTableRef.getTableData();
  }
};

const emit = defineEmits(["chooseGroup"]);
const handleCheck = (data) => {
  let idArr = [];
  tree.value.getCheckedNodes().forEach((item) => {
    if (item.type == 'category') {
      if (item.child) {
        idArr = idArr.concat(item.child);
      }
    } else if (item.type == 'device') {
      idArr.push(item);
    }
  });
  idArr = Array.from(new Set(idArr))
  emit(
    "chooseGroup",
    idArr.map(item => {
      return item.deviceId
    })
  );
};
const pidlist = ref([]);
watch(searchKeys, (val, oldValue) => {
  pidlist.value = [];
  treeData.value[0].child.forEach((item) => {
    if (item.name.includes(val)) {
      pidlist.value.push(item.id);
    }
  });
  tree.value.filter(val);
});
</script>

<style lang="scss" scoped>
#myGroup {
  width: 286px;
  // border-left: 1px solid #eee;
  padding: 32px 24px;
  h1 {
    // display: flex;
    // justify-content: space-between;
    // align-items: center;
    // line-height: 42px;
    // width: 100%;
    // padding: 0 10px 0 20px;
    // border-bottom: 1px solid #f4f5f9;
    font-size: 18px;
    font-weight: 500;
  }
  .search {
    padding: 16px 0;
    :deep(.el-input-group__append) {
      width: 32px;
      background: #fff;
    }
  }
  .custom-tree-node {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    .node-lable {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      padding-right: 25px;
      i {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-image: linear-gradient(#ffb340 0, #ff9900 100%);
      }
      .is-online {
        background-image: linear-gradient(#24ec60 0, #1fe159 100%);
      }
      p {
        max-width: 90px;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      span {
        display: inline-block;
        max-width: 80px;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 12px;
        text-align: right;
      }
    }
  }
  :deep(.el-tree-node__content) {
    height: 40px;
  }
  :deep(.el-tree>.el-tree-node>.el-tree-node__content:first-child) {
    background-color: #EEF2F7;
    border-radius: 4px;
  }
  // :deep(.node-disabled .el-tree-node__content) {
  //   cursor: no-drop;
  // }
  :deep(.node-level3 .el-tree-node__content) {
    padding-left: 18px !important;
  }
  :deep(.node-level3 .node-lable) {
    justify-content: flex-start;
    padding: 0;
    p {
      max-width: 150px;
      margin-left: 10px;
    }
  }
}
</style>
